//
// Created by hugan on 2020/11/22.
//

#include "CharsetConverter.h"

int CharsetConverter::multi2uni(const std::string &multi, std::wstring &uni, UINT code) {
    auto len = MultiByteToWideChar(code, 0, multi.c_str(), -1, nullptr, 0);
    if (len <= 0) {
        std::cerr << __FILE__ << " : " << __LINE__ << " : " << GetLastError() << std::endl;
        return -1;
    }
    auto *buf = new WCHAR[len];
    len = MultiByteToWideChar(code, 0, multi.c_str(), -1, buf, len);
    uni.assign(buf);
    delete[]buf;
    return len;
}

int CharsetConverter::uni2multi(const std::wstring &uni, std::string &multi, UINT code) {
    auto len = WideCharToMultiByte(code, 0, uni.c_str(), -1, nullptr, 0, nullptr, nullptr);
    if (len <= 0) {
        std::cerr << __FILE__ << " : " << __LINE__ << " : " << GetLastError() << std::endl;
        return -1;
    }
    CHAR *buf = new CHAR[len];
    len = WideCharToMultiByte(code, 0, uni.c_str(), -1, buf, len, nullptr, nullptr);
    multi.assign(buf);
    delete[]buf;
    return len;
}

int CharsetConverter::ansi2uni(const std::string &ansi, std::wstring &uni) {
    return multi2uni(ansi, uni, CP_ACP);
}

int CharsetConverter::uni2ansi(const std::wstring &uni, std::string &ansi) {
    return uni2multi(uni, ansi, CP_ACP);
}

int CharsetConverter::utf82uni(const std::string &utf8, std::wstring &uni) {
    return multi2uni(utf8, uni, CP_UTF8);
}

int CharsetConverter::uni2utf8(const std::wstring &uni, std::string &utf8) {
    return uni2multi(uni, utf8, CP_UTF8);
}

int CharsetConverter::ansi2utf8(const std::string &ansi, std::string &utf8) {
    std::wstring uni;
    auto len = ansi2uni(ansi, uni);
    if (len <= 0) {
        return -3;
    }
    return uni2utf8(uni, utf8);
}

int CharsetConverter::utf82ansi(const std::string &utf8, std::string &ansi) {
    std::wstring uni;
    auto len = utf82uni(utf8, uni);
    if (len <= 0) {
        return -3;
    }
    return uni2ansi(uni, ansi);
}

void CharsetConverter::jString2ansi(JNIEnv *env, jstring &str, std::string &ansi) {
    const char *p1;
    p1 = env->GetStringUTFChars(str, JNI_FALSE);
    env->ReleaseStringUTFChars(str, p1);
    CharsetConverter::utf82ansi(p1, ansi);
}

